<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ page import="java.util.Date" %>
<%@ page import="cn.estore.dao.OrderDao" %>
<%@ page import="cn.estore.dao.ProductDao" %>
<%@ page import="cn.estore.entity.Order" %>
<%@ page import="cn.estore.entity.Product" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>购买商品结果</title>
</head>
<body>
<%
    // 获取商品ID和购买数量参数
    int productId = Integer.parseInt(request.getParameter("productId"));
    int quantity = Integer.parseInt(request.getParameter("quantity"));

    // 获取当前用户的ID，这里假设通过查找名为"user_id"的Cookie来获取（实际需根据登录逻辑准确获取）
    int userId = 0;
    Cookie[] cookies = request.getCookies();
    if (cookies!= null) {
        for (Cookie cookie : cookies) {
            if ("user_id".equals(cookie.getName())) {
                userId = Integer.parseInt(cookie.getValue());
                break;
            }
        }
    }

    // 获取商品信息用于计算价格等（这里简化处理，实际可能需更多校验和逻辑）
    ProductDao productDao = new ProductDao();
    Product product = null;
    try {
        product = productDao.selectProductById(productId);
    } catch (Exception e) {
        out.println("<p>获取商品信息出现异常，请稍后再试。</p>");
        e.printStackTrace();
    }

    if (product!= null) {
        double actualPrice = product.getMarketPrice(); // 这里假设实际价格就是市场价格，可根据实际优惠等调整
        double totalAmount = actualPrice * quantity;

        Order order = new Order();
        order.setUserId(userId);
        order.setProductId(productId);
        order.setProductQuantity(quantity);
        order.setActualPrice(actualPrice);
        order.setTotalAmount(totalAmount);
        // 生成订单编号，这里简单示例，实际需按更合理规则生成
        String orderNumber = "ORDER_" + System.currentTimeMillis();
        order.setOrderNumber(orderNumber);

        OrderDao orderDao = new OrderDao();
        boolean insertSuccess = false;
        try {
            insertSuccess = orderDao.insertOrder(order);
        } catch (Exception e) {
            out.println("<p>订单插入出现异常，请稍后再试。</p>");
            e.printStackTrace();
        }

        if (insertSuccess) {
            out.println("<p>订单插入成功，感谢您的购买！您的订单编号为：" + orderNumber + "</p>");
        } else {
            out.println("<p>订单插入失败，请检查信息后重试。</p>");
        }
    }
%>
</body>
</html>
